<style lang="less">
  .organization_resource{
    display: flex;
    flex-direction: column;
    .el-tree {
      overflow: auto;
    }
  }
</style>

<template>
  <div class="organization_resource">
    <div style="margin-bottom: 10px">
      <el-button type="primary" @click="saveResources" :disabled="organizationId == null">保存</el-button>
    </div>
    <ue-el-tree
      ref="myTree"
      check-strictly
      :data="resourceTree"
      default-expand-all
      show-checkbox
      node-key="id"
      :props="{children: 'children',label: 'name'}">
    </ue-el-tree>
  </div>
</template>

<script>
import { resourceTree } from '../../../api/organization/resource';
import {
  addResource, getResource
} from '../../../api/organization/Organization';
export default {
  name: 'OrganizationResource',
  componentName: 'OrganizationResource',
  data () {
    return {
      organizationId: null,
      resourceTree: []
    };
  },
  methods: {
    setCheckedKeys (id) {
      this.organizationId = id;
      getResource(id).then(res => {
        if (res.data.successFlg) {
          this.$refs.myTree.setCheckedKeys(res.data.detailModelList);
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    saveResources () {
      let ids = this.$refs.myTree.getCheckedKeys(false);
      if (ids.length === 0) {
        this.$message('请选择一些资源!');
        return;
      }
      let resources = ids.map(item => {
        return {id: item};
      });

      addResource(this.organizationId, resources).then(res => {
        if (res.data.successFlg) {
          this.$message('保存成功!');
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    }
  },
  mounted () {
    resourceTree().then(res => {
      if (res.data.successFlg) {
        this.resourceTree = res.data.detailModelList;
        this.$ue.handleTreeItem(this.resourceTree, item => {
          if (item.type === 'BUTTON') {
            item.icon = 'fa fa-hand-pointer-o';
          } else if (item.type === 'QUERY') {
            item.icon = 'fa fa-search';
          }
        });
      } else {
        this.$message.error(res.data.errorMsg);
      }
    });
  }
};
</script>
